package com.caption.interceptor;

import com.caption.utils.IdGenerator;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AuthenticationInterceptor implements HandlerInterceptor {
    /**
     * ThreadContext.put(),ThreadContext.get(), ThreadContext.clearAll()这种方式可以日志打印出来请求流水号
     * ThreadContext.push(),ThreadContext.peek(),ThreadContext.pop()这种方式可以从上下文中获取请求流水号
     * TODO 注意链路执行完成之后必须清除txnId, 不然会造成内存泄露（ThreadContext本身维护的是ThreadLocal）
     *
     * @param request
     * @param response
     * @param object
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) {
        ThreadContext.pop();
        ThreadContext.clearAll();
        //设置请求流水号,微服务模块从请求头获取,单体应用自己生成
        //String txnId = request.getHeader("txnId");
        String txnId =  IdGenerator.getInstance().nextId();
        ThreadContext.put("txnId", txnId);
        ThreadContext.push(txnId);
        return true;
    }


    //请求时处理
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    //请求后处理
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        ThreadContext.pop();
        ThreadContext.clearAll();
    }
}
